﻿using Common.Model;
using Common.Utility;
using NPOI.HSSF.Record;
using Stylet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WeighingRecord.Models;
using WeighingRecord.Services;

namespace WeighingRecord.ViewModels
{
    public class ReuploadAllProgressViewModel : Screen
    {
        private static readonly log4net.ILog log = LogHelper.GetLogger();

        private string _text = "请稍后...";
        public string Text
        {
            get
            {
                return _text;
            }
            set
            {
                SetAndNotify(ref _text, value);
            }
        }

        private string _summaryText = $"成功:0 失败:0";
        public string SummaryText
        {
            get
            {
                return _summaryText;
            }
            set
            {
                SetAndNotify(ref _summaryText, value);
            }
        }

        private double _total = 100;
        public double Total
        {
            get
            {
                return _total;
            }
            set
            {
                SetAndNotify(ref _total, value);
            }
        }

        private double _current;
        public double Current
        {
            get
            {
                return _current;
            }
            set
            {
                SetAndNotify(ref _current, value);
            }
        }

        private List<WeighingRecordModel> _records;

        private int _success;
        private int _failure;

        private IWindowManager _windowManager;
        /// <summary>
        /// 创建窗体
        /// </summary>
        public ReuploadAllProgressViewModel(IWindowManager windowManager, List<WeighingRecordModel> records)
        {
            _windowManager = windowManager;
            _records = records;
            Total = _records.Count;

            var worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;

            var uploader = Common.Platform.PlatformManager.Instance.Current;

            var model = new CleanupConfig.ProgressReportModel();

            var channelNo = SettingsHelper.AWSV2Settings.Settings["platformChannel"]?.Value ?? string.Empty;

            worker.DoWork += (s, e) =>
            {
                var index = 1;
                var state = 0;
                foreach (var item in _records)
                {
                    model.Current = index;
                    model.Text = $"正在上传：{item.Bh}";

                    try
                    {
                        uploader.UploadWeighingData((Common.Models.WeighingRecordModel)item,
                        channelNo, string.Empty, string.Empty);
                        item.IsUpload = true;
                        SQLDataAccess.UpdateWeighingRecord(item);
                        state = 1;
                    }
                    catch (Exception ex)
                    {
                        state = 0;
                        log.Error($"{item.Bh}-{item.Ch} 上传数据失败: 平台:{uploader.Name}", ex);
                    }

                    Thread.Sleep(100);

                    worker.ReportProgress(state, model);
                    index++;
                }

                model.Text = $"处理完毕";
                worker.ReportProgress(-1, model);
                e.Result = model;

            };

            worker.ProgressChanged += (s, e) =>
            {
                var m = e.UserState as CleanupConfig.ProgressReportModel;

                Text = m.Text;
                Current = m.Current;
                if (e.ProgressPercentage == 0)
                {
                    _failure += 1;
                }
                else if (e.ProgressPercentage == 1)
                {
                    _success += 1;
                }
                SummaryText = $"成功:{_success} 失败:{_failure}";
                //Total = m.Total;
            };

            worker.RunWorkerCompleted += async (s, e) =>
            {
                var ret = e.Result as CleanupConfig.ProgressReportModel;
                Text = e.Error?.Message ?? ret.Text;

                await Task.Delay(2500);

                this.RequestClose();

            };

            worker.RunWorkerAsync();
        }
    }
}
